package com.yidushishizijie.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    /*//定义SqlSessionFactory
    private static SqlSessionFactory factory = null;

    static {
        //使用静态代码块创建一次SqlSessionFactoy
        String config = "mybatis.xml";
        try {
            //读取配置文件
            InputStream in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession对象
    public static SqlSession getSqlSession(){
        SqlSession session =null;
        if (factory != null){
            session = factory.openSession();
        }
        return session;
    }

    //提交事务
    public static void getCommit(){
        SqlSession session = getSqlSession();
        if (session == null){
            return;
        }
        session.commit();
    }*/

    private static SqlSessionFactory factory = null;
    static {
        String config = "mybatis.xml";//需要和你项目中的文件名一样
        try {
            InputStream in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象，使用SqlSessionFactoryBuild
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取sqlSession的方法
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if(factory != null){
            sqlSession = factory.openSession();//非自动提交事务
        }
        return sqlSession;
    }
}
